<template>
    <div>
        <Button type="success" @click="modal1= true" >增贴</Button>
        <Button type="error" @click="removes">删除多个</Button>
         <Input search  v-model="input2" placeholder="请输入文章名" :style="{width:200+'px'}" />
        <!-- <input type="text" v-model="input2" placeholder="请输入文章分类名">  -->
        <Button type="success" @click="sousuo" >搜索</Button>
        <Modal
                v-model = "modal1"
                title   = "发布美照竞赛贴"
                :mask-closable="false"
                :loading  = "loading"
                @on-ok  = "asyncOK">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="90">
                <FormItem label="文章分类名" prop='input'>
                    <Input v-model="formValidate.input" placeholder="请填入文章的分类"></Input>
                </FormItem>
                 <FormItem label="文章名" prop='input1'>
                    <Input v-model="formValidate.input1" placeholder="请填入文章的名"></Input>
                </FormItem>
                <FormItem label="宠物类别" prop='select'>
                    <Select v-model="formValidate.select">
                        <Option value="猫">猫</Option>
                        <Option value="狗">狗</Option>
                        <Option value="其他">其他</Option>
                    </Select>
                </FormItem>
                <div class="upimgBox">
<div class="container">
<div class="upload_warp_left" @click="fileClick" >
<div class="addNote">+</div>
</div>
<!-- <div class="upload_warp_text">
选中{{imgList.length}}张文件，共{{bytesToSize(this.size)}}; 最多上传<span class="text-primary"> 6</span> 张图片！
</div> -->
<div class="upload_warp">
<div class="upload_warp_img" v-show="imgList.length!=0" >
<div class="upload_warp_img_div" v-for="(item,index) of imgList" :key="index">
<div class="upload_warp_img_div_top" >
<div class="upload_warp_img_div_del" @click="fileDel(index)">X</div>
</div>
<img :src="item.file.src">
</div>
</div>
</div>
<!-- <span v-for="(item,index) of imgSrc" :key="index">
          <img :src="item.file.src" alt="" @click="removetu(index)">
</span> -->
<input @change="fileChange($event)" type="file" id="upload_file" multiple style="display: none"/>
</div>
</div>
                <FormItem label="帖子内容" prop="desc">
                    <Input v-model="formValidate.desc" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入帖子内容"></Input>
                </FormItem>

                 <FormItem label="奖品内容" prop="desc1">
                    <Input v-model="formValidate.desc1" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入奖品项"></Input>
                </FormItem>
                 <FormItem label="起始时间" prop='date'>
                    <Row>
                        <Col span="11">
                            <DatePicker type="date" placeholder="Select date" v-model="formValidate.date"></DatePicker>
                        </Col>
                        <Col span="2" style="text-align: center">-</Col>
                        <Col span="11">
                            <FormItem prop="time">
                            <TimePicker type="time" placeholder="Select time" v-model="formValidate.time"></TimePicker>
                            </FormItem>
                        </Col>
                    </Row>
                </FormItem>
                <FormItem label="结束时间" prop='date1'>
                    <Row>
                        <Col span="11">
                            <DatePicker type="date" placeholder="Select date" v-model="formValidate.date1"></DatePicker>
                        </Col>
                        <Col span="2" style="text-align: center">-</Col>
                        <Col span="11">
                            <FormItem prop="time1">
                               <TimePicker type="time" placeholder="Select time" v-model="formValidate.time1"></TimePicker>
                            </FormItem>
                        </Col>
                    </Row>
                </FormItem>
                <FormItem >
                    <Button type="primary" @click="handleSubmit('formValidate')" >提交</Button>
                    <Button @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
                </FormItem>
            </Form>
             <div slot="footer">
            </div>
            </Modal>
             <Modal
        v-model="modal3"
        title="竞赛帖详情"
       >
        <p>文章分类名：{{this.data[this.index1].acname}}</p>
        <p>文章名：{{this.data[this.index1].articalname}}</p>
        <p>作者名：：{{this.data[this.index1].authorname}}</p>
        <p>创建时间：{{this.data[this.index1].createtime}}</p>
        <p>宠物分类：{{this.data[this.index1].petclassify}}</p> 
        <span>样图</span>
       <span v-for="(item,index) of this.data[this.index1].imgsrc" :key="index">
          <img :src="item.file.src" alt="" >
       </span>
        <p>帖子内容：{{this.data[this.index1].content}}</p>
        <p>奖品：{{this.data[this.index1].prize}}</p>
        <p>比赛开始时间：{{this.data[this.index1].starttime}}</p>
        <p>比赛开始时间：{{this.data[this.index1].endtime}}</p>
    </Modal>
        <Table border ref="selection" :columns="columns1" :data="data" @on-selection-change="onSelect"></Table>
        <Page :total="total" :page-size="list" @on-change="onChangePage" :page-size-opts=[5,10,15,20] @on-page-size-change="onPageSizeChange" show-sizer />
    </div>
</template>
<script>
export default {
  data() {
    return {
      srczc:'',//存放获取的图片路径
      z: "",
      index1: 0,
      modal3: false,
      imgList: [],
      imgSrc: [],
      size: 0,
      x: [],
      srcstring: "",
      weburl: "http://10.31.162.59:3000/photo",
      input2: "",
      input3: "",
      data: [],
      total: 0,
      page: 1,
      list: 5,
      formValidate: {
        input: "",
        input1: "",
        select: "",
        date: "",
        time: "",
        date1: "",
        time1: "",
        desc: "",
        desc1: ""
      },
      ruleValidate: {
        input: [
          {
            required: true,
            type: "string",
            message: "请输入文章分类名",
            trigger: "change"
          }
        ],
        input1: [
          {
            required: true,
            type: "string",
            message: "请输入文章名",
            trigger: "change"
          }
        ],
        select: [
          {
            required: true,
            type: "string",
            message: "请选择宠物分类",
            trigger: "change"
          }
        ],
        date: [
          {
            required: true,
            type: "date",
            message: "Please select the date",
            trigger: "change"
          }
        ],
        time: [
          {
            required: true,
            type: "string",
            message: "Please select time",
            trigger: "change"
          }
        ],
        date1: [
          {
            required: true,
            type: "date",
            message: "Please select the date",
            trigger: "change"
          }
        ],
        time1: [
          {
            required: true,
            type: "string",
            message: "Please select time",
            trigger: "change"
          }
        ],
        desc: [
          {
            required: true,
            message: "Please enter a personal introduction",
            trigger: "blur"
          },
          {
            type: "string",
            min: 20,
            message: "Introduce no less than 20 words",
            trigger: "blur"
          }
        ],
        desc1: [
          {
            required: true,
            message: "Please enter a personal introduction",
            trigger: "blur"
          },
          {
            type: "string",
            min: 20,
            message: "Introduce no less than 20 words",
            trigger: "blur"
          }
        ]
      },
      modal1: false,
      loading: true,
      removesdata: [],
      columns1: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "文章分类名",
          key: "acname",
          render: (h, params) => {
            return h("div", [
              h("Icon", {
                props: {
                  type: "person"
                }
              }),
              h("strong", params.row.acname)
            ]);
          }
        },
        {
          title: "文章名",
          key: "articalname"
        },
        {
          title: "作者名",
          key: "authorname"
        },
        {
          title: "创建时间",
          key: "createtime"
        },
        {
          title: "宠物分类",
          key: "petclassify"
        },
        {
          title: "功能",
          key: "action",
          width: 200,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.show(params.index);
                      this.modal3 = true;
                    }
                  }
                },
                "查看"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "warning",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.edit(params.row._id);
                    }
                  }
                },
                "修改"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      console.log(params);
                      this.remove(params.row._id);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ]
    }
  },
  methods: {
    show(index) {
      this.index1 = index;
    },
    sousuo() {
      console.log(this.input2);
      this.axios({
        method: "post",
        url: `${this.weburl}/list`,
        data: {
          page: this.page,
          limit: this.list,
          articalname: this.input2
        }
      }).then(res => {
        this.total = res.data.total;
        this.data = res.data.docs;
      });
    },
    remove(id) {
      this.$Modal.confirm({
        title: "确认操作",
        content: "<p>你确认删除该记录吗?</p>",
        onOk: () => {
          this.axios({
            url: `${this.weburl}/${id}`,
            method: "delete"
          }).then(res => {
            alert("你已经删除成功");
            this.getData();
          });
        },
        onCancel: () => {
          this.$Message.info("Clicked cancel");
        }
      });
    },
    getData() {
      this.axios({
        method: "post",
        url: `${this.weburl}/list`,
        data: {
          page: this.page,
          limit: this.list
        }
      }).then(res => {
        this.total = res.data.total;
        this.data = res.data.docs;
      });
    },
    asyncOK() {
      setTimeout(() => {
        this.modal1 = false;
      }, 2000);
    },
    onSelect(selections) {
      var ids = [];
      for (let i = 0; i < selections.length; i++) {
        ids.push(selections[i]._id);
      }
      this.ids = ids.toString();
      console.log(this.ids);
    },
    // 多选删除
    removes() {
      this.$Modal.confirm({
        title: "确认操作",
        content: "<p>你确认删除该记录吗?</p>",
        onOk: () => {
          this.axios({
            url: `${this.weburl}/`,
            method: "delete",
            data: {
              ids: this.ids
            }
          }).then(res => {
            alert("你已经删除成功");
            this.getData();
          });
        },
        onCancel: () => {
          this.$Message.info("Clicked cancel");
        }
      });
    },
    // 在此函数进行帖子提交
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        var starttimel = new Date(this.formValidate.date);
        var starttimeleft = starttimel.toLocaleDateString();
        var endtimel = new Date(this.formValidate.date1);
        var endtimeleft = endtimel.toLocaleDateString();
        let starttime = starttimeleft + " " + this.formValidate.time;
        let endtime = endtimeleft + " " + this.formValidate.time1;
        //修改的
        if (this.formValidate._id) {
          this.axios({
            url: `${this.weburl}/${this.formValidate._id}`,
            method: "put",
            data: {
              acname: this.formValidate.input,
              articalname: this.formValidate.input1,
              petclassify: this.formValidate.select,
              imgsrc:this.imgList,
              content: this.formValidate.desc,
              prize: this.formValidate.desc1,
              starttime: starttime,
              endtime: endtime
            }
          }).then(res => {
            this.modal1 = false;
             this.imgList=[];
              this.imgSrc=[];
            this.$refs[name].resetFields();
            this.getData();
          });
        } else {
        //  第一次提交的
          this.axios({
            method: "post",
            url: `${this.weburl}`,
            data: {
              acname: this.formValidate.input,
              articalname: this.formValidate.input1,
              authorname: "官方",
              createtime:
                new Date().toLocaleDateString() +
                " " +
                new Date().toLocaleTimeString(),
              petclassify: this.formValidate.select,
              imgsrc: this.imgList,
              content: this.formValidate.desc,
              prize: this.formValidate.desc1,
              starttime: starttime,
              endtime: endtime
            }
          }).then(res => {
             this.imgList=[];
          this.imgSrc=[];
            this.modal1 = false;
            this.$refs[name].resetFields();
            this.getData();
          });
        }
      });
    },
    handleReset(name) {
      this.$refs[name].resetFields();
    },
    edit(id) {
      console.log("修改啊");
      this.axios({
        url: `${this.weburl}/${id}`,
        method: "get"
      }).then(res => {
        this.formValidate = res.data;
        this.formValidate.input = res.data.acname;
        this.formValidate.input1 = res.data.articalname;
        this.formValidate.select = res.data.petclassify;
        this.imgList=res.data.imgsrc;
        this.formValidate.desc = res.data.content;
        this.formValidate.desc1 = res.data.prize;
        this.formValidate.date = res.data.starttime.split(" ")[0];
        this.formValidate.time = res.data.starttime.split(" ")[1];
        this.formValidate.date1 = res.data.endtime.split(" ")[0];
        this.formValidate.time1 = res.data.endtime.split(" ")[1];
        this.modal1 = true;
      });
    },
    onChangePage(page) {
      this.page = page;
      if (this.input2 != "") {
        this.sousuo();
      } else {
        this.getData();
      }
    },
    onPageSizeChange(list) {
      console.log(list);
      this.list = list;
      if (this.input2 != "") {
        this.sousuo();
      } else {
        this.getData();
      }
    },
    //修改图片
  //   removetu(index){
  //     console.log(index);
  //      this.$Modal.confirm({
  //       title: "确认操作",
  //       content: "<p>你确认删除该记录吗?</p>",
  //       onOk: () => {
  //       this.imgSrc.splice(index,1);
  //       },
  //       onCancel: () => {
  //         this.$Message.info("Clicked cancel");
  //       }
  //   })
  // },
    //上传图片
    fileClick() {
      document.getElementById("upload_file").click();
    },
    fileChange(el) {
      if (!el.target.files[0].size) return;
      this.fileList(el.target.files);
      el.target.value = "";
    },
    fileList(files) {
      for (let i = 0; i < files.length; i++) {
        this.fileAdd(files[i]);
      }
    },
    fileAdd(file) {
      // console.log(file, "54321");
      this.size = this.size + file.size; //总大小
      let reader = new FileReader();
      reader.vue = this;
      if (this.imgList.length <= 5) {
        //判断限制图片上传张数
        reader.readAsDataURL(file);
        reader.onload = function() {
          file.src = this.result;
          this.vue.imgList.push({
            file
          });
        };
        // console.log(this.imgList, "12345");
      } else {
        this.$toast("最多上传四张图片");
      }
    },
    fileDel(index) {
      this.size = this.size - this.imgList[index].file.size; //总大小
      this.imgList.splice(index, 1);
    },
    bytesToSize(bytes) {
      if (bytes === 0) return "0 B";
      let k = 1000, // or 1024
        sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
        i = Math.floor(Math.log(bytes) / Math.log(k));
      return (bytes / Math.pow(k, i)).toPrecision(3) + " " + sizes[i];
    },
    dragenter(el) {
      el.stopPropagation();
      el.preventDefault();
    },
    dragover(el) {
      el.stopPropagation();
      el.preventDefault();
    },
    drop(el) {
      el.stopPropagation();
      el.preventDefault();
      this.fileList(el.dataTransfer.files);
    }
  },
  mounted() {
    this.getData();
  }
};
</script>

<style scoped>
.upload_warp_img_div_del {
  width: 16px;
  right: 4px;
}

.upload_warp_img_div_top {
  position: absolute;
  top: 0;
  width: 100%;
  height: 20px;
  background-color: rgba(0, 0, 0, 0.4);
  color: #fff;
  font-size: 12px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  /* border:1px solid red; */
}

.upload_warp_img_div img {
  width: 100%;
  height: 100%;
}

.upload_warp_img_div {
  position: relative;
  height: 73px;
  width: 73px;
  border: 1px solid #ccc;
  margin: 0px 10px 5px 0px;
  float: left;
  text-align: center;
  background-color: #eee;
  cursor: pointer;
  /* border:1px solid red; */
}

.upload_warp_img {
  width: 100%;
  /* border-top: 1px solid #d2d2d2; */
  padding: 5px 0 0 8px;
  overflow: hidden;
  margin-top: 10px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  /* border: 1px solid black; */
}

/* .upload_warp_text {
text-align: left;
margin-bottom: 5px;
padding-top: 5px;
text-indent: 14px;
border-top: 1px solid #ccc;
font-size: 14px;
border:1px solid red;
} */

.upload_warp_right {
  float: left;
  width: 57%;
  margin-left: 2%;
  height: 100%;
  border-radius: 4px;
  line-height: 130px;
  color: #999;
}

.addNote {
  width: 60px;
  height: 60px;
  margin: 7px 5px 0px 8px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 45px;
  color: #bbbbbb;
  border: 1px solid #bbbbbb;
}

.upload_warp_left {
  float: left;
  width: 100%;
  height: 80px;
  /* border: 1px solid red; */
}

.upload_warp {
  width: 100%;
  height: auto;
  display: flex;
  justify-content: space-around;
  align-items: center;
  /* border:1px solid black !important; */
}

.container {
  width: 97%;
  /* height: 80px; */
  background-color: #fff;
  padding: 3px;
  margin: 0 auto;
  /* border:1px solid green; */
}

.upimgBox {
  width: 100%;
  /* text-align: center; */
}
img {
  width: 70px !important;
}

</style>


